home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: gail.ripco.com!mambuhl
- From: mambuhl@ripco.com (Martin Ambuhl)
- Subject: Re: pseudo-random numbers
- X-Nntp-Posting-Host: foley.ripco.com
- Message-ID: <DL02pB.H7C@rci.ripco.com>
- Sender: usenet@rci.ripco.com (Net News Admin)
- Organization: Ripco Internet BBS Chicago
- Date: Thu, 11 Jan 1996 04:48:47 GMT
- X-Ident-Sender: mambuhl
-
- JJSTEP00@ukcc.uky.edu (Jason Stephenson)
- in <17709D420S86.JJSTEP00@ukcc.uky.edu> asks:
-
- >I know what the c.l.c. FAQ says about pseudo-random numbers, so I wonder why
- >I seem to get "better" results with "rand() % n + 1" than I get when I use
- >"n * rand() / RAND_MAX + 1" Am I missing some parenthesis or something?
-
- Yes.
-
- You might find these macros useful:
- #define random(num) (int)(((long)rand()*(num))/(RAND_MAX+1))
- #define randomize() srand((unsigned)time(NULL))
-
- Notice that the macro random(num) evaluates to a value in the range
- 0...num-1. You should restrict num to the range of an int.
-
- Also, you could rewrite the macro so it returns a double
- #define halfopen_random() ((double)rand()/(RAND_MAX+1)) /* [0,1) */
- #define closed_random() ((double)rand()/(RAND_MAX)) /* [0,1] */
-
-
-
- >Oh yeah, and I usually call "srand(clock())" once in the initialization of
- >my program. With the first, I get an integer between 1 and n. With the
- >second, I almost always get a value of 1 or 2.
-
-
- --
- * Martin Ambuhl net: mambuhl@ripco.com
- * Chicago, IL (USA)
-